import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:xiaofanshu_flutter/apis/app.dart';
import 'package:xiaofanshu_flutter/components/timer_count.dart';
import 'package:xiaofanshu_flutter/static/custom_code.dart';
import 'package:xiaofanshu_flutter/static/custom_string.dart';
import 'package:xiaofanshu_flutter/utils/snackbar_util.dart';
import 'package:xiaofanshu_flutter/utils/parameter_verification.dart';

class ResetPasswordController extends GetxController {
  var phoneNumber = ''.obs;
  var smsCode = ''.obs;
  var password = ''.obs;
  var confirmPassword = ''.obs;
  var isLoading = false.obs;

  void resetPassword() async {
    if (phoneNumber.value.isEmpty) {
      SnackbarUtil.showError('请输入手机号');
      return;
    }

    if (!ParameterVerification.isPhoneNumber(phoneNumber.value)) {
      SnackbarUtil.showError('请输入正确的手机号');
      return;
    }

    if (smsCode.value.isEmpty) {
      SnackbarUtil.showError('请输入验证码');
      return;
    }

    if (password.value.isEmpty) {
      SnackbarUtil.showError('请输入新密码');
      return;
    }

    if (password.value.length < 6) {
      SnackbarUtil.showError('密码长度至少6位');
      return;
    }

    if (confirmPassword.value != password.value) {
      SnackbarUtil.showError('两次输入的密码不一致');
      return;
    }

    isLoading.value = true;
    try {
      var response = await UserApi.resetPassword(
        phoneNumber.value,
        password.value,
        smsCode.value,
      );

      if (response.code == StatusCode.postSuccess) {
        SnackbarUtil.showSuccess('密码重置成功');
        Get.back();
      } else {
        SnackbarUtil.showError(response.msg ?? '密码重置失败');
      }
    } catch (e) {
      SnackbarUtil.showError('网络错误，请重试');
    } finally {
      isLoading.value = false;
    }
  }

  void sendSmsCode() async {
    if (phoneNumber.value.isEmpty) {
      SnackbarUtil.showError('请输入手机号');
      return;
    }

    if (!ParameterVerification.isPhoneNumber(phoneNumber.value)) {
      SnackbarUtil.showError('请输入正确的手机号');
      return;
    }

    try {
      var response = await ThirdApi.sendResetPhoneSms(phoneNumber.value);
      if (response.code == StatusCode.getSuccess) {
        SnackbarUtil.showSuccess('验证码已发送');
      } else {
        SnackbarUtil.showError(response.msg ?? '发送验证码失败');
      }
    } catch (e) {
      SnackbarUtil.showError('发送验证码失败');
    }
  }

  Future<bool> sendSmsCodeWithResult() async {
    if (phoneNumber.value.isEmpty) {
      SnackbarUtil.showError('请输入手机号');
      return false;
    }

    if (!ParameterVerification.isPhoneNumber(phoneNumber.value)) {
      SnackbarUtil.showError('请输入正确的手机号');
      return false;
    }

    try {
      var response = await ThirdApi.sendResetPhoneSms(phoneNumber.value);
      if (response.code == StatusCode.getSuccess) {
        SnackbarUtil.showSuccess('验证码已发送');
        return true;
      } else {
        SnackbarUtil.showError(response.msg ?? '发送验证码失败');
        return false;
      }
    } catch (e) {
      SnackbarUtil.showError('发送验证码失败');
      return false;
    }
  }
}

class ResetPasswordPage extends StatelessWidget {
  ResetPasswordPage({Key? key}) : super(key: key);

  final ResetPasswordController controller = Get.put(ResetPasswordController());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xfff5f5f5),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: true,
        title: const Text(
          '修改密码',
          style: TextStyle(color: Colors.black, fontSize: 18),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Get.back(),
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              margin: const EdgeInsets.all(20),
              padding: const EdgeInsets.all(20),
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(20)),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '手机号',
                    style: TextStyle(fontSize: 14, color: Color(0xff666666)),
                  ),
                  const SizedBox(height: 10),
                  TextField(
                    keyboardType: TextInputType.phone,
                    inputFormatters: [
                      LengthLimitingTextInputFormatter(11),
                      FilteringTextInputFormatter.digitsOnly,
                    ],
                    decoration: InputDecoration(
                      hintText: '请输入手机号',
                      hintStyle: const TextStyle(
                        color: Color(0xffcccccc),
                        fontSize: 16,
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(
                          color: Color(0xffe5e5e5),
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(
                          color: Color(0xffe5e5e5),
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(
                          color: Color(0xff4a90e2),
                        ),
                      ),
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 15,
                        vertical: 15,
                      ),
                    ),
                    onChanged: (value) => controller.phoneNumber.value = value,
                  ),
                  const SizedBox(height: 20),
                  const Text(
                    '验证码',
                    style: TextStyle(fontSize: 14, color: Color(0xff666666)),
                  ),
                  const SizedBox(height: 10),
                  Row(
                    children: [
                      Expanded(
                        child: TextField(
                          keyboardType: TextInputType.number,
                          inputFormatters: [
                            LengthLimitingTextInputFormatter(6),
                            FilteringTextInputFormatter.digitsOnly,
                          ],
                          decoration: InputDecoration(
                            hintText: '请输入验证码',
                            hintStyle: const TextStyle(
                              color: Color(0xffcccccc),
                              fontSize: 16,
                            ),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10),
                              borderSide: const BorderSide(
                                color: Color(0xffe5e5e5),
                              ),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10),
                              borderSide: const BorderSide(
                                color: Color(0xffe5e5e5),
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(10),
                              borderSide: const BorderSide(
                                color: Color(0xff4a90e2),
                              ),
                            ),
                            contentPadding: const EdgeInsets.symmetric(
                              horizontal: 15,
                              vertical: 15,
                            ),
                          ),
                          onChanged: (value) => controller.smsCode.value = value,
                        ),
                      ),
                      const SizedBox(width: 10),
                      SendSmsBtn(
                        onTap: () async {
                          return await controller.sendSmsCodeWithResult();
                        },
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),
                  const Text(
                    '新密码',
                    style: TextStyle(fontSize: 14, color: Color(0xff666666)),
                  ),
                  const SizedBox(height: 10),
                  TextField(
                    obscureText: true,
                    decoration: InputDecoration(
                      hintText: '请输入新密码',
                      hintStyle: const TextStyle(
                        color: Color(0xffcccccc),
                        fontSize: 16,
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(
                          color: Color(0xffe5e5e5),
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(
                          color: Color(0xffe5e5e5),
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(
                          color: Color(0xff4a90e2),
                        ),
                      ),
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 15,
                        vertical: 15,
                      ),
                    ),
                    onChanged: (value) => controller.password.value = value,
                  ),
                  const SizedBox(height: 20),
                  const Text(
                    '确认密码',
                    style: TextStyle(fontSize: 14, color: Color(0xff666666)),
                  ),
                  const SizedBox(height: 10),
                  TextField(
                    obscureText: true,
                    decoration: InputDecoration(
                      hintText: '请再次输入新密码',
                      hintStyle: const TextStyle(
                        color: Color(0xffcccccc),
                        fontSize: 16,
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(
                          color: Color(0xffe5e5e5),
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(
                          color: Color(0xffe5e5e5),
                        ),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10),
                        borderSide: const BorderSide(
                          color: Color(0xff4a90e2),
                        ),
                      ),
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 15,
                        vertical: 15,
                      ),
                    ),
                    onChanged: (value) => controller.confirmPassword.value = value,
                  ),
                  const SizedBox(height: 30),
                  SizedBox(
                    width: double.infinity,
                    height: 50,
                    child: ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xff4a90e2),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(25),
                        ),
                        elevation: 0,
                      ),
                      onPressed: () => controller.resetPassword(),
                      child: Obx(() => controller.isLoading.value
                          ? const SizedBox(
                              width: 20,
                              height: 20,
                              child: CircularProgressIndicator(
                                strokeWidth: 2,
                                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                              ),
                            )
                          : const Text(
                              '确认修改',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                              ),
                            )),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}